package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    @Resource
    private DishMapper dishMapper;
    @Resource
    private DishFlavorMapper dishFlavorMapper;
    @Resource
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    @Transactional // 开启事务管理 注解
    public void saveDishAndFlavor(DishDTO dishDTO) {

        //向菜品表插入1条数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.insert(dish);

        //获取添加时主键的id值
        Long id = dish.getId();

        //向口味表插入n条数据
        List<DishFlavor> flavors = dishDTO.getFlavors();

        if(flavors != null && flavors.size() > 0){
            flavors.forEach(flavor -> {
               flavor.setDishId(id);
            });
            //批量插入
            dishFlavorMapper.insertBatch(flavors);

        }
    }

    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.page(dishPageQueryDTO);
        Long total = page.getTotal();
        List<DishVO> dishList = page.getResult();
        return new PageResult(total, dishList);
    }

    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
        //菜品是否能够删除？ --起售中的菜品不能删除
        for(Long id : ids){
            Dish dish = dishMapper.findById(id);
            if(dish.getStatus() == StatusConstant.ENABLE){
                //处于起售中,不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //是否被套餐关联？
        List<Long> setmealIds = setmealDishMapper.getSetmealDishIdsBySetmealId(ids);
        if(setmealIds != null && setmealIds.size() > 0){
            //当前菜品关联了套餐,不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //遍历删除
        //删除菜品表中的菜品数据
//       for(Long id : ids){
//           dishMapper.deleteById(id);
//           //删除菜品关联的口味数据
//           dishFlavorMapper.deleteByDishId(id);
//       }

       //批量删除  代码优化
        //删除菜品表中的菜品数据
        //sql: delete from dish where id in (1,2,3,4)
        dishMapper.deleteByIds(ids);
        //删除菜品关联的口味数据
        //sql: delete from dish_flavor where dish_id in (1,2,3,4)
        dishFlavorMapper.deleteByIds(ids);



    }

    @Override
    @Transactional
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //修改菜品表基本信息
        dishMapper.update(dish);
        //删除原有的口味数据
        dishFlavorMapper.deleteByDishId(dish.getId());
        //重新插入口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors != null && flavors.size() > 0){
            flavors.forEach(flavor -> {
                flavor.setDishId(dish.getId());
            });
            dishFlavorMapper.insertBatch(flavors);
        }

    }

    @Override
    public DishVO getByIdWithFlavor(Long id){
        //根据id查询菜品数据
        Dish dish = dishMapper.findById(id);
        //根据菜品id查询口味数据
        List<DishFlavor> dishFlavors =  dishFlavorMapper.getByDishId(id);

        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavors);

        return dishVO;
    }
    @Override
    public void updateStatus(Integer status,Long id){
        Dish dish = new Dish();
        dish.setId(id);
        dish.setStatus(status);
        dishMapper.update(dish);
    }

    @Override
    public List<Dish> list(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        return dishMapper.list(dish);
    }
    @Transactional
    @Override
    public List<DishVO> getByCategoryIdWithFlavors(Long categoryId) {
        //根据 categoryId 菜品分类id 查找 相应菜品

//        String key = "dish_"+categoryId;
//        List<DishVO> list = (List<DishVO>) redisTemplate.opsForValue().get(key);
//        if(list != null && list.size() > 0){
//            return list;
//        }
        List<DishVO> list = new ArrayList<>();

        List<Dish> dishList = dishMapper.findByCategoryId(categoryId,1);
        //根据 菜品id  查找口味数据
        for (Dish dish : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish, dishVO);
            List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(dish.getId());
            if(dishFlavors != null && dishFlavors.size() > 0){
                dishVO.setFlavors(dishFlavors);
            }
            System.out.println("dishVO="+dishVO);
            list.add(dishVO);
        }
        //设置缓存
//        redisTemplate.opsForValue().set(key,list);

        return list;

    }


}
